package com.duowei.diandan.db;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.WorkerThread;

import com.duowei.diandan.bean.Desk;
import com.duowei.diandan.bean.DeskGroup;
import com.duowei.diandan.bean.DeskStatus;
import com.duowei.diandan.db.entry.Jycssz;

import java.util.ArrayList;
import java.util.List;

/**
 * 餐桌列表
 */
public class DeskList {
    private static DeskList sDeskList;

    private List<DeskGroup> deskGroupList = new ArrayList<>();
    private List<Desk> allDeskList = new ArrayList<>();

    private Handler mHandler;

    public DeskList() {
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static DeskList getInstance() {
        if (sDeskList == null) {
            sDeskList = new DeskList();
        }

        return sDeskList;
    }

    @WorkerThread
    public void createGroupList() {
        this.deskGroupList.clear();
        this.allDeskList.clear();

        AppDatabase db = AppDatabase.getDatabase();
        List<Jycssz> cates = db.jycsszDao().findCates();
        if (cates.size() == 0) {
            this.deskGroupList.clear();
        } else {
            for (Jycssz cate : cates) {
                List<Jycssz> jycsszList = db.jycsszDao().findChildsByCsbh(cate.getCsbh());
                if (jycsszList.size() > 0) {
                    List<Desk> deskList = new ArrayList<>();
                    for (Jycssz jycssz : jycsszList) {
                        deskList.add(new Desk(jycssz));
                    }
                    this.allDeskList.addAll(deskList);

                    DeskGroup deskGroup = new DeskGroup(cate.getCsbh(), cate.getCsmc(), deskList);
                    this.deskGroupList.add(deskGroup);
                }
            }

            DeskGroup allDeskGroup = new DeskGroup(true, null, "全部", allDeskList);
            this.deskGroupList.add(0, allDeskGroup);
        }
    }

    @WorkerThread
    public void handleDeskStatus(List<DeskStatus> deskStatusList) {
        for (Desk d : this.allDeskList) {
            List<DeskStatus> dsList = new ArrayList<>();
            for (DeskStatus ds : deskStatusList) {
                if (d.getJycssz().getCsbh().equals(ds.getCsbh())) {
                    dsList.add(ds);
                }
            }

            if (!d.getDeskStatusList().containsAll(dsList)
                    || !dsList.containsAll(d.getDeskStatusList())) {
                d.getDeskStatusList().clear();
                d.getDeskStatusList().addAll(dsList);
                mHandler.post(d::setDataChanged);
            }
        }
    }

    public void addAll(List<DeskGroup> deskGroupList) {
        if (deskGroupList != null) {
            this.deskGroupList.addAll(deskGroupList);
        }
    }

    public List<DeskGroup> getDeskGroupList() {
        return deskGroupList;
    }

    public List<Desk> getAllDeskList() {
        return this.allDeskList;
    }
}
